package com.fly.socket.schedule;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;

import com.fly.socket.po.Message;
import com.fly.socket.websocket.MyWebSocketHandler;
import com.google.gson.GsonBuilder;

@Component
public class ScheduleJob implements SchedulingConfigurer
{
    private static final Logger logger = LoggerFactory.getLogger(ScheduleJob.class);
    
    @Autowired
    MyWebSocketHandler handler;
    
    int num = 10;
    
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar)
    {
        taskRegistrar.addTriggerTask(() -> doJob(), new Trigger()
        {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext)
            {
                // 任务触发，可修改任务的执行周期
                return new PeriodicTrigger(num, TimeUnit.SECONDS).nextExecutionTime(triggerContext);
            }
        });
    }
    
    public void doJob()
    {
        try
        {
            logger.info("------------start scheduleJob------------");
            Message msg = new Message();
            msg.setDate(new Date());
            msg.setFrom(-1L);
            msg.setFromName("系统广播");
            msg.setTo(0L);
            num = RandomUtils.nextInt(0, 60);
            msg.setText(String.format("随机内容：%s,下次消息%s秒后。。。", RandomStringUtils.randomNumeric(10), num));
            String text = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg);
            handler.broadcast(new TextMessage(text));
        }
        catch (IOException e)
        {
            logger.error("broadcast error", e);
        }
    }
}
